package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.entity.SysUser;
import com.ktjy.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService {

    @Autowired
    SysUserMapper sysUserMapper;


    /**
     * 根据用户名查找用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUsrName, username);

        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        } else {//
            List authorities = new ArrayList();
            User user = new User(username,
                    new BCryptPasswordEncoder().encode(sysUser.getUsrPassword()),
                    authorities);
            return user;
        }
    }
}
